package com.xy.test.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class AppClient implements Serializable {

    public void run() {

        // 定义线程池, EventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();

        // 启动一个客户端需要一个辅助类, bootstrap
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress(7777))
                    // 选择初始化一个什么样的channel
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MyChannelHandLer2());
                        }
                    });

            // 尝试连接服务器
            ChannelFuture channelFuture = bootstrap.connect().sync();
            // 获取 channel, 并且写出数据
            channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("Hello Netty".getBytes(StandardCharsets.UTF_8)));

            // 阻塞等待服务器返回数据
            channelFuture.channel().closeFuture().sync();
            group.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        new AppClient().run();
    }
}
